#!/usr/bin/env python
# -*- coding: UTF8 -*-
from __future__ import division

""" docstring """

__author__      = "Hao FengGe (xxhfg@163.com)"
__version__     = "@Revision: 0.1 $"
__date__        = "@Update  : 2011/03/18 09:40:28 $"
__copyright__   = "Copyright (c) 2010 Hao FengGe"
__license__     = "Python"

import time
import re
from random import * 
import sqlite3
from lottery_qxc import INSERT_DATA_ERROR

def rules_1(data):
    """规则1 for rules_1
    根据最新数据与历史数据的差值判断候选号码
    """
    if (not isinstance(data, (list, list))) or (len(data)==0):
        raise DATA_FORMAT_ERROR('数据格式错误！')

    # rules1 = { -9:0, -8:0, -7:0, -6:0, -5:0, -4:0, -3:0, -2:0, -1:0, 0:0, 1:0,
            # 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0}
    # rulers1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    # rulers1 = { '-9':0, '-8':0, '-7':0, '-6':0, '-5':0, '-4':0, '-3':0, '-2':0,
            # '-1':0, '0':0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0,
            # '8':0, '9':0}
    rulers1 = {}
    rulers2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    total = 0
    for j in range(1, 51):
        for i in range(j, len(data)):
            cur = data[i]
            # last_data = [data[i - j]]
            last_data = data[i - j:i]
            # msg = ' %s ---- ' % cur[0] 
            # Out_Msg(msg)
            rulers2[cur[1]] += 1
            for dat in last_data:
                total += 1
                # rulers1[str(cur[1] - dat[1])] = rulers1[str(cur[1] - dat[1])] + 1 \
                        # if str(cur[1] - dat[1]) in rulers1 else 1
                rulers1[str(cur[1] - dat[1])] = rulers1[str(cur[1] - dat[1])] + 1 \
                        if str(cur[1] - dat[1]) in rulers1 else 1

        print 'j = %d ---- ' % j
        # print rulers1
        keys = []
        for k in rulers1.keys():
            keys.append(int(k))
        # keys = rulers1.keys()
        keys.sort()
        result = {}
        # result = {}.fromkeys(rulers1.keys())
        for key in keys:
            # result.update({str(key): round(rulers1[str(key)] / total * 100, 2)})
            print "%2s ---- %5d ---- %5d ---- %2.2f" % (str(key), rulers1[str(key)], total, round(rulers1[str(key)] / total * 100, 2))
        print result
        # time.sleep(5)
        rulers1 = {}
        total = 0
    print rulers2


def rules_2(data):
    """规则二 for rules_2
    根据最新数据与历史数据重复率选择候选号码
    """
    if (not isinstance(data, (list, list))) or (len(data)==0):
        raise DATA_FORMAT_ERROR('数据格式错误！')

    rules1 = {}
    total = 0
    for j in range(1, 51):
        for i in range(j, len(data)):
            cur = data[i]
            last_data = data[i - j:i]
            for dat in last_data:
                total += 1
                if cur[1] == dat[1]:
                    rules1[str(cur[1])] = rules1[str(cur[1])] + 1 \
                        if str(cur[1]) in rules1 else 1
        print 'j = %d ---- %5d' % (j, total)
        # print rules1
        result = {}
        for key in rules1.keys():
            result[key] = round(rules1[key] / total * 100, 2)
        
        print result
        rules1 = {}
        total = 0

def rules_3(data):
    """规则3 for rules_3
    根据最新数据与历史数据重复率选择候选号码
    """
    if (not isinstance(data, (list, list))) or (len(data)==0):
        raise DATA_FORMAT_ERROR('数据格式错误！')

    rules1 = {}
    total = 0
    for i in range(1, len(data)):
        cur = data[i]
        print cur[0] + ' ---- '
        for j in range(1, 51):
            if i < j:
                break

            last_data = data[i - j:i]
            for dat in last_data:
                total += 1
                if cur[1] == dat[1]:
                    rules1[str(cur[1])] = rules1[str(cur[1])] + 1 \
                        if str(cur[1]) in rules1 else 1
            print 'j = %d ---- %5d' % (j, total)
        # print rules1
        result = {}
        for key in rules1.keys():
            result[key] = round(rules1[key] / total * 100, 2)
        
        print result
        rules1 = {}
        total = 0

def rules_4(data):
    """规则4 for rules_4
    根据最新数据与历史数据方差选择候选号码
    """
    if (not isinstance(data, (list, list))) or (len(data)==0):
        raise DATA_FORMAT_ERROR('数据格式错误！')

    rules1 = {}
    total = 0

    for i in range(1, len(data)):
        cur = data[i]
        print 'cur : '
        print cur
        j = 10
        if i < j:
            continue
        else:
            last_data = [data[i - j]]
            for last in last_data:
                print 'last : '
                print last
                fc = (int(cur[1]) - int(last[1])) ** 2
                print fc
                fc = fc % 3
                print fc
                rules1[fc] = rules1[fc] + 1 if fc in rules1 else 1
    print rules1
    pass

def guess_rules4(data):
    """按照规则4进行猜测 for guess_rules4"""
    if (not isinstance(data, (list, list))) or (len(data)==0):
        raise DATA_FORMAT_ERROR('数据格式错误！')

    rules1 = {}
    total = 0
    result = {"0":0, "1":0}

    for i in range(1, len(data)):
        cur = data[i]
        print ''
        print ' ------ '
        print cur
        j = 5
        if i < j:
            last_data = data[0:i]
        else:
            last_data = data[i - j:i]
        print ' ------ %d' % len(last_data)
        n = int(cur[1])
        guess1 = {}
        guess2 = {}
        guess3 = {}
        guess4 = {}
        guess5 = {}
        guess6 = {}
        guess7 = {}
        for last in last_data:
            print last
            m = int(last[1])
            for k in range(10):
                # fc = (m - k) ** 2
                # print fc
                fc = (int(last[1]) - k) ** 2
                if fc%3 == 1:
                    guess1[str(k)]=guess1[str(k)] + 1 if str(k) in guess1 else 1
                fc = (int(last[2]) - k) ** 2
                if fc%3 == 1:
                    guess2[str(k)]=guess2[str(k)] + 1 if str(k) in guess2 else 1
                fc = (int(last[3]) - k) ** 2
                if fc%3 == 1:
                    guess3[str(k)]=guess3[str(k)] + 1 if str(k) in guess3 else 1
                fc = (int(last[4]) - k) ** 2
                if fc%3 == 1:
                    guess4[str(k)]=guess4[str(k)] + 1 if str(k) in guess4 else 1
                fc = (int(last[5]) - k) ** 2
                if fc%3 == 1:
                    guess5[str(k)]=guess5[str(k)] + 1 if str(k) in guess5 else 1
                fc = (int(last[6]) - k) ** 2
                if fc%3 == 1:
                    guess6[str(k)]=guess6[str(k)] + 1 if str(k) in guess6 else 1
                fc = (int(last[7]) - k) ** 2
                if fc%3 == 1:
                    guess7[str(k)]=guess7[str(k)] + 1 if str(k) in guess7 else 1

        value1 = guess1.values()
        max_value = max(value1)
        guess1_new = {}
        for key in guess1:
            if  guess1[key] == max_value:
                guess1_new[key] = max_value

        value2 = guess2.values()
        max_value = max(value2)
        guess2_new = {}
        for key in guess2:
            if  guess2[key] == max_value:
                guess2_new[key] = max_value

        value3 = guess3.values()
        max_value = max(value3)
        guess3_new = {}
        for key in guess3:
            if  guess3[key] == max_value:
                guess3_new[key] = max_value

        value4 = guess4.values()
        max_value = max(value4)
        guess4_new = {}
        for key in guess4:
            if  guess4[key] == max_value:
                guess4_new[key] = max_value

        value5 = guess5.values()
        max_value = max(value5)
        guess5_new = {}
        for key in guess5:
            if  guess5[key] == max_value:
                guess5_new[key] = max_value

        value6 = guess6.values()
        max_value = max(value6)
        guess6_new = {}
        for key in guess6:
            if  guess6[key] == max_value:
                guess6_new[key] = max_value

        value7 = guess7.values()
        max_value = max(value7)
        guess7_new = {}
        for key in guess7:
            if  guess7[key] == max_value:
                guess7_new[key] = max_value

        guess_in = 0
        # guess1_new = {'0':0, '1':0, '2':0}
        if str(cur[1]) in guess1_new:
            guess_in += 1
        # if str(cur[2]) in guess2_new:
            # guess_in += 1
        # if str(cur[3]) in guess3_new:
            # guess_in += 1
        # if str(cur[4]) in guess4_new:
            # guess_in += 1
        # if str(cur[5]) in guess5_new:
            # guess_in += 1
        # if str(cur[6]) in guess6_new:
            # guess_in += 1
        # if str(cur[7]) in guess7_new:
            # guess_in += 1
        print guess1_new
        print guess2_new
        print guess3_new
        print guess4_new
        print guess5_new
        print guess6_new
        print guess7_new
        print "Count ---- %d" % (len(guess1_new) * len(guess2_new) * len(guess3_new) * len(guess4_new) * len(guess5_new) * len(guess6_new) * len(guess7_new))
        # if str(cur[1]) in guess1_new and str(cur[1]) in guess2_new and str(cur[1]) in guess3_new and str(cur[1]) in guess4_new and str(cur[1]) in guess5_new and str(cur[1]) in guess6_new and str(cur[1]) in guess7_new:
        if guess_in >= 1:
            print "One : successed!"
            result["1"] += 1
        else:
            print "One : failed!"
            result["0"] += 1
        # time.sleep(5)
    print result


def guess_rules5(data):
    """按照规则5进行猜测 for guess_rules5"""
    if (not isinstance(data, (list, list))) or (len(data)==0):
        raise DATA_FORMAT_ERROR('数据格式错误！')

    successed = 0
    failed = 0
    focus = {}
    result = {}
    result_all = {}

    for m in range(1, 8):
        result_all[m] = {}

    for i in range(0, len(data)):
        cur = data[i]
        print ''
        print ' ------ %d' % (i + 1)
        print cur
        j = 50
        if i < j:
            last_data = data[0:i]
        else:
            last_data = data[i - j:i]
        print result_all

        result_last = {}
        for m in range(1, 8):
            result_last[m] = {}

        for dat in last_data:
            # print dat
            for m in range(1, 8):
                result_last_tmp = result_last[m] if m in result_last else {}
                result_last_tmp[dat[m]] = result_last_tmp[dat[m]] + 1 if dat[m] in result_last_tmp else 1
                result_last[m] = result_last_tmp

        print result_last
        print ' ------ %d' % len(last_data)


        total = 1
        for m in range(1, 8):
            guess = []
            tmp = {}
            for k in range(10):
                if not (k in result_all[m] and k in result_last[m]):
                    guess.append(k)
                else:
                    if  (result_all[m][k] / i) / (result_last[m][k] / len(last_data)) > 1.0:
                        guess.append(k)

            result[m] = guess
            total *= len(guess)
        print result
        print ' ------ '

        count = 1
        if i > j:
            for m in range(1, 8):
                guess = result[m]
                if guess.count(cur[m]) > 0:
                    print '%d focused' % m
                    focus[m] = focus[m] + 1 if m in focus else 1
                    count *= 10
        print ' ------ '
        print 'total is %d' % total
        print 'count is %d' % count
        if count > total and count > 100:
        # if count > 100:
            successed += 1


        for m in range(1, 8):
            result_all_tmp = result_all[m] if m in result_all else {}
            result_all_tmp[cur[m]] = result_all_tmp[cur[m]] + 1 if cur[m] in result_all_tmp else 1
            result_all[m] = result_all_tmp

    print ' ------ '
    print focus
    print ' ------ '
    print 'successed is %d' % successed

def guess_rules6(data):
    """按照规则6进行猜测 for guess_rules6"""
    if (not isinstance(data, (list, list))) or (len(data)==0):
        raise DATA_FORMAT_ERROR('数据格式错误！')

    guess = {}
    for k in range(0, 10):
        guess[k] = 0

    success1 = 0
    success2 = 0
    dat_1 = []
    for i in range(0, len(data)):
        cur = data[i]
        print cur

        j = 10
        if i < j:
            last_data = data[0:i]
        else:
            last_data = data[i - j:i]
        dat_1_last = []
        for dat in last_data:
            dat_1_last.append(dat[1])

        print ' ------ '
        print dat_1_last
        if len(dat_1_last) > 0:
            choice_last = choice(dat_1_last)
            print 'choice1 ------ %d' % choice_last
            if cur[1] == choice_last:
                success1 += 1
                print 'success1 ------ %d' % success1
        print dat_1
        if len(dat_1) > 0:
            choice_cur = choice(dat_1)
            print 'choice2 ------ %d' % choice_cur
            if cur[1] == choice_cur:
                success2 += 1
                print 'success2 ------ %d' % success2
        print ''

        dat_1.append(cur[1])

    print 'success1 ------ %d' % success1
    print 'success2 ------ %d' % success2

def get_rules_one(data):
    """得到规则1 for get_rules_one
    规则1：各位数字长期出现比率和短期出现比率的比值
    参数：data ---- 历史数据
    返回值：规则数据
    """
    if (not isinstance(data, (list, list))) or (len(data)==0):
        raise DATA_FORMAT_ERROR('数据格式错误！')


    """
    l = len(data)   #总期数
    j = 50  #短期期数
    for i in range(j, l): 
        cur_data = data[i] #最新数据

        short_data = data[i - j:i]  #短期数据
        long_data = data[:i]  #长期数据

        long_rules = {}     #长期比率
        short_rules = {}    #短期比率
        for m in range(1, 8):
            long_rules[m] = {}
            short_rules[m] = {}

        for s_data in short_data:
            for m in range(1, 8):
                short_rules[m][s_data[m]] = short_rules[m][s_data[m]] + 1 \
                        if s_data[m] in short_rules[m] else 1

        for l_data in long_data:
            for m in range(1, 8):
                long_rules[m][l_data[m]] = long_rules[m][l_data[m]] + 1 \
                        if l_data[m] in long_rules[m] else 1

        result = {}
        for m in range(1, 8):
            result[m] = {}
            for n in range(0, 10):
                if (n in long_rules[m]) and (n in short_rules[m]):
                    result[m][n] = round((long_rules[m][n] / len(long_data)) / (short_rules[m][n] / len(short_data)), 3)
                else:
                    result[m][n] = 0

        print cur_data
        print short_rules
        print long_rules
        print ' ------ '
        print result
        print ' ------ '
        print ''
    """

    long_rules = {}
    short_rules = {}
    result = {}
    for m in range(1, 8):
        long_rules[m] = {}
        short_rules[m] = {}
        result[m] = {}
        for n in range(0, 10):
            long_rules[m][n] = 0
            short_rules[m][n] = 0
            result[m][n] = 0

    for l_data in data:
        for m in range(1, 8):
            long_rules[m][l_data[m]] += 1

    i = len(data)
    j = 50
    short_data = data[i - j:i]
    for s_data in short_data:
        for m in range(1, 8):
            short_rules[m][s_data[m]] += 1

    for m in range(1, 8):
        for n in range(0, 10):
            if short_rules[m][n] > 0:
                result[m][n] = round((long_rules[m][n] / len(data)) / (short_rules[m][n] / len(short_data)), 3)
            else:
                result[m][n] = 10

    return result

def get_rules_two(data):
    """得到规则2 for get_rules_two
    规则2：相邻数字相互匹配次数
    参数：data ---- 历史数据
    返回值：规则数据
    """
    if (not isinstance(data, (list, list))) or (len(data)==0):
        raise DATA_FORMAT_ERROR('数据格式错误！')

    result = {}
    for m in range(1, 7):
        for n in range(m + 1, 8):
            if m != n:
                k = str(m) + ' - ' + str(n)
                result[k] = {}
                for i in range(0, 10):
                    for j in range(0, 10):
                        key = str(i) + str(j)
                        result[k][key] = 0

    for l_data in data:
        for m in range(1, 7):
            for n in range(m + 1, 8):
                if m != n:
                    k = str(m) + ' - ' + str(n)
                    key = str(l_data[m]) + str(l_data[n])
                    result[k][key] += 1

    return result

def guess_lottery(data):
    """猜测开奖号码 for guess_lottery
    根据历史数据猜测开奖号码
    参数：data ---- 历史数据
    返回值：开奖数据
    """
    if (not isinstance(data, (list, list))) or (len(data)==0):
        raise DATA_FORMAT_ERROR('数据格式错误！')

    print "Bgein ------ "

    # for dat in data:
        # print str(dat[1]) + str(dat[2]) + str(dat[3]) + str(dat[4]) + \
                # str(dat[5]) + str(dat[6]) + str(dat[7])
    # print " ------ "

    rules_1 = get_rules_one(data)
    # for n, r in rules_1.items():
        # print n, r
    rules_2 = get_rules_two(data)
    # for n, r in rules_2.items():
        # print n, r

    result = []
    haoma = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    try:
        db = sqlite3.connect('caipiao.db')
        cursor = db.cursor()

        cursor.execute('delete from lottery')
        db.commit()

        for m1 in haoma:
            for m2 in haoma:
                for m3 in haoma:
                    for m4 in haoma:
                        for m5 in haoma:
                            for m6 in haoma:
                                for m7 in haoma:
                                    key = m1 + m2 + m3 + m4 + m5 + m6 + m7

                                    y1 = rules_1[1][int(m1)]
                                    y2 = rules_1[1][int(m2)]
                                    y3 = rules_1[1][int(m3)]
                                    y4 = rules_1[1][int(m4)]
                                    y5 = rules_1[1][int(m5)]
                                    y6 = rules_1[1][int(m6)]
                                    y7 = rules_1[1][int(m7)]

                                    tmp_value = 1
                                    for m in range(1, 7):
                                        for n in range(m + 1, 8):
                                            if m != n:
                                                k = str(m) + ' - ' + str(n)
                                                # print key
                                                # print m, n
                                                k2 = key[m - 1] + key[n - 1]
                                                tmp_value *= rules_2[k][k2]
                                    value = round(y1 * y2 * y3 * y4 * y5 * y6 * y7 * tmp_value * len(data), 9)
                                    # k1 = m1 + m2
                                    # k2 = m2 + m3
                                    # k3 = m3 + m4
                                    # k4 = m4 + m5
                                    # k5 = m5 + m6
                                    # k6 = m6 + m7

                                    # v1 =  rules_2[1][k1]
                                    # v2 =  rules_2[2][k2]
                                    # v3 =  rules_2[3][k3]
                                    # v4 =  rules_2[4][k4]
                                    # v5 =  rules_2[5][k5]
                                    # v6 =  rules_2[6][k6]

                                    # value = round(y1 * y2 * y3 * y4 * y5 * y6 * y7 * \
                                            # v1 * v2 * v3 * v4 * v5 * v6, 3)

                                    # lottery[key] = value
                                    if int(key) / 100000 == int(key) // 100000:
                                        print int(key) // 100000
                                        db.commit()


                                    cursor.execute('insert into lottery values(?, ?)', \
                                            (key, value))
        db.commit()

        cursor.execute('select * from lottery order by value desc limit 100000')
        for row in cursor:
            result.append(row)
    except sqlite3.DatabaseError, exc:
        #error = exc.args
        #print "ErrorCode: " + str(error)
        error = "ErrorCode: " + str(exc.args)
        raise INSERT_DATA_ERROR(error)
    finally:
        db.close()

    lottery = {}
    for k, v in result:
        lottery[k] = 1
        # print k
        # 匹配4-7位连续的数字
        pattern = r"""(?:(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|
                7(?=8)|8(?=9)){3,}|(?:9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|
                4(?=3)|3(?=2)|2(?=1)|1(?=0)){3,})"""
        if re.search(pattern, k) is not None:
            # print "match one"
            lottery[k] = 0
        # 匹配两个3位以上的连续重复数字
        pattern = r"([\d])\1{2,}\d*?([\d])\1{2,}"
        if re.search(pattern, k) is not None:
            # print "match two"
            lottery[k] = 0
        # 匹配4位以上的相同数字
        pattern = r"\d*?([\d])\d*?\1\d*?\1\d*?\1\d*?"
        if re.search(pattern, k) is not None:
            # print "match three"
            lottery[k] = 0
        # 匹配aabbcc的连续重复数字
        pattern = r"\d*?([\d])\1{1,}\d*?([\d])\2{1,}\d*?([\d])\3{1,}\d*?"
        if re.search(pattern, k) is not None:
            # print "match four"
            lottery[k] = 0

    items = lottery.items()
    # for k, v in items:
        # if v == 1:
            # print k, v
    print " ------ "
    i = 0
    while i < 5:
        # j = randrange(len(lottery))
        # item = lottery[j]
        item = choice(items)
        k, v = item
        if v == 1:
            print k, v
            i += 1
    print "End ------ "

if __name__=='__main__':
    pass

